<template>
  <transition name="toolbar-fade">
    <div v-if="visible" class="inline-toolbar" :style="toolbarStyle" @mousedown.prevent.self>
      <!-- 字体选择 -->
      <div class="toolbar-item dropdown-container">
        <button
          class="toolbar-btn font-btn"
          title="字体"
          @click="toggleFontDropdown"
          @mousedown.prevent
        >
          <Type class="icon" />
          <span class="font-name">{{ currentFontName }}</span>
          <ChevronDown class="icon-small" />
        </button>
        <div
          v-if="showFontDropdown"
          class="dropdown-menu font-dropdown"
          :class="{ 'dropdown-right': shouldAlignRight }"
        >
          <div class="color-dropdown-title">选择字体</div>
          <div
            v-for="font in fonts"
            :key="font.value"
            class="dropdown-item"
            :class="{ active: currentFormat.fontFamily === font.value }"
            :style="{ fontFamily: font.value }"
            @click="applyFormat('fontFamily', font.value)"
          >
            {{ font.label }}
          </div>
        </div>
      </div>

      <!-- 字体大小选择 -->
      <div class="toolbar-item dropdown-container">
        <button
          class="toolbar-btn font-size-btn"
          title="字体大小"
          @click="toggleFontSizeDropdown"
          @mousedown.prevent
        >
          <Type class="icon" />
          <span class="font-size-text">{{ currentFontSizeText }}</span>
          <ChevronDown class="icon-small" />
        </button>
        <div
          v-if="showFontSizeDropdown"
          class="dropdown-menu font-size-dropdown"
          :class="{ 'dropdown-right': shouldAlignRight }"
        >
          <div class="color-dropdown-title">选择字体大小</div>
          <div
            v-for="size in fontSizes"
            :key="size.value"
            class="dropdown-item"
            :class="{ active: currentFormat.fontSize === size.value }"
            @click="applyFontSize(size)"
          >
            <span class="size-label">{{ size.label }}</span>
            <span class="size-value">{{ size.value }}</span>
          </div>
        </div>
      </div>

      <div class="toolbar-divider"></div>

      <!-- 对齐选项 -->
      <button
        class="toolbar-btn"
        :class="{ active: currentFormat.textAlign === 'left' }"
        title="左对齐"
        @click="applyFormat('textAlign', 'left')"
        @mousedown.prevent
      >
        <AlignLeft class="icon" />
      </button>
      <button
        class="toolbar-btn"
        :class="{ active: currentFormat.textAlign === 'center' }"
        title="居中"
        @click="applyFormat('textAlign', 'center')"
        @mousedown.prevent
      >
        <AlignCenter class="icon" />
      </button>
      <button
        class="toolbar-btn"
        :class="{ active: currentFormat.textAlign === 'right' }"
        title="右对齐"
        @click="applyFormat('textAlign', 'right')"
        @mousedown.prevent
      >
        <AlignRight class="icon" />
      </button>

      <div class="toolbar-divider"></div>

      <!-- 文本格式 -->
      <button
        class="toolbar-btn"
        :class="{ active: currentFormat.bold }"
        title="加粗 (Ctrl+B)"
        @click="applyFormat('bold')"
        @mousedown.prevent
      >
        <Bold class="icon" />
      </button>
      <button
        class="toolbar-btn"
        :class="{ active: currentFormat.italic }"
        title="斜体 (Ctrl+I)"
        @click="applyFormat('italic')"
        @mousedown.prevent
      >
        <Italic class="icon" />
      </button>
      <button
        class="toolbar-btn"
        :class="{ active: currentFormat.underline }"
        title="下划线 (Ctrl+U)"
        @click="applyFormat('underline')"
        @mousedown.prevent
      >
        <Underline class="icon" />
      </button>
      <button
        class="toolbar-btn"
        :class="{ active: currentFormat.strikethrough }"
        title="删除线"
        @click="applyFormat('strikethrough')"
        @mousedown.prevent
      >
        <Strikethrough class="icon" />
      </button>

      <div class="toolbar-divider"></div>

      <!-- 链接 -->
      <button class="toolbar-btn" title="插入链接" @click="insertLink" @mousedown.prevent>
        <Link class="icon" />
      </button>

      <!-- 代码块 -->
      <button
        class="toolbar-btn"
        :class="{ active: currentFormat.code }"
        title="代码"
        @click="applyFormat('code')"
        @mousedown.prevent
      >
        <Code class="icon" />
      </button>

      <div class="toolbar-divider"></div>

      <!-- 颜色选择器 -->
      <div class="toolbar-item dropdown-container">
        <button
          class="toolbar-btn color-picker-btn"
          title="颜色"
          @click="toggleColorPicker"
          @mousedown.prevent
        >
          <Palette class="icon" />
          <div class="color-indicators">
            <div
              class="color-indicator text-color"
              :style="{ backgroundColor: currentFormat.color || '#000000' }"
              title="文字颜色"
            ></div>
            <div
              class="color-indicator bg-color"
              :style="{ backgroundColor: currentFormat.backgroundColor || 'transparent' }"
              title="背景色"
            ></div>
          </div>
        </button>
        <div
          v-if="showColorPicker"
          class="dropdown-menu color-picker-dropdown"
          :class="{ 'dropdown-right': shouldAlignRight }"
        >
          <!-- 颜色模式标签 -->
          <div class="color-mode-tabs">
            <button
              class="color-tab"
              :class="{ active: colorMode === 'text' }"
              @click="setColorMode('text')"
            >
              字体颜色
            </button>
            <button
              class="color-tab"
              :class="{ active: colorMode === 'background' }"
              @click="setColorMode('background')"
            >
              背景颜色
            </button>
          </div>

          <!-- 颜色网格 -->
          <div class="color-content">
            <div class="color-grid">
              <div
                v-for="color in currentColors"
                :key="color"
                class="color-item"
                :class="{ active: isColorActive(color) }"
                :style="{ backgroundColor: color }"
                @click="applyColorFormat(color)"
                :title="getColorTitle(color)"
              ></div>
            </div>

            <!-- 自定义颜色区域 -->
            <div class="custom-color-section">
              <div class="custom-color-title">自定义颜色</div>
              <input
                type="color"
                class="custom-color-input"
                :value="getCustomColorValue()"
                @change="applyCustomColor"
              />
              <button class="reset-color-btn" @click="resetColor" title="重置颜色"> 重置 </button>
            </div>
          </div>
        </div>
      </div>

      <div class="toolbar-divider"></div>

      <!-- 更多选项 -->
      <button class="toolbar-btn" title="更多选项" @click="showMoreOptions" @mousedown.prevent>
        <MoreHorizontal class="icon" />
      </button>
    </div>
  </transition>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import {
  Type,
  ChevronDown,
  AlignLeft,
  AlignCenter,
  AlignRight,
  Bold,
  Italic,
  Underline,
  Strikethrough,
  Link,
  Code,
  Palette,
  MoreHorizontal
} from 'lucide-vue-next'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  position: {
    type: Object,
    default: () => ({ x: 0, y: 0 })
  },
  selectionRect: {
    type: Object,
    default: null
  },
  currentFormat: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['format', 'insert-link', 'more-options'])

const showFontDropdown = ref(false)
const showFontSizeDropdown = ref(false)
const showColorPicker = ref(false)
const colorMode = ref('text') // 'text' | 'background'

const fonts = [
  { label: '宋体', value: 'SimSun' },
  { label: '黑体', value: 'SimHei' },
  { label: '微软雅黑', value: 'Microsoft YaHei' },
  { label: '楷体', value: 'KaiTi' },
  { label: '仿宋', value: 'FangSong' },
  { label: 'Arial', value: 'Arial' },
  { label: 'Times New Roman', value: 'Times New Roman' }
]

const fontSizes = [
  { label: '极小', value: '10px' },
  { label: '小', value: '12px' },
  { label: '较小', value: '14px' },
  { label: '正常', value: '16px' },
  { label: '较大', value: '18px' },
  { label: '大', value: '20px' },
  { label: '特大', value: '24px' },
  { label: '超大', value: '28px' },
  { label: '巨大', value: '32px' },
  { label: '超巨大', value: '36px' }
]

// 文字颜色选项
const textColors = [
  'inherit', // 默认颜色（透明选项）
  '#000000',
  '#333333',
  '#666666',
  '#999999',
  '#ff0000',
  '#00ff00',
  '#0000ff',
  '#ffff00',
  '#ff6600',
  '#ff00ff',
  '#00ffff',
  '#800080',
  '#008000',
  '#800000',
  '#000080',
  '#808000',
  '#ffa500',
  '#ff1493',
  '#00ced1',
  '#32cd32'
]

// 背景颜色选项
const backgroundColors = [
  'transparent',
  '#ffff00',
  '#00ff00',
  '#00ffff',
  '#ff00ff',
  '#ff6666',
  '#66ff66',
  '#6666ff',
  '#ffcc66',
  '#ff99cc',
  '#99ccff',
  '#ccff99',
  '#ffccff',
  '#ffd700',
  '#40e0d0',
  '#ff69b4',
  '#ba55d3'
]

const toolbarStyle = computed(() => {
  const style = {
    left: `${props.position.x}px`,
    top: `${props.position.y}px`,
    transform: 'translateX(-50%)' // 水平居中
  }

  // 确保工具栏不超出视口
  if (props.visible && props.selectionRect) {
    const toolbarWidth = 520 // 估算的工具栏宽度
    const toolbarHeight = 40 // 工具栏高度
    const viewportWidth = window.innerWidth
    const viewportHeight = window.innerHeight
    const halfWidth = toolbarWidth / 2
    const gap = 10

    // 水平位置调整
    if (props.position.x + halfWidth > viewportWidth - 20) {
      // 右边界调整 - 去掉transform，直接设置右对齐
      style.left = `${viewportWidth - toolbarWidth - 20}px`
      style.transform = 'none'
    } else if (props.position.x - halfWidth < 20) {
      // 左边界调整 - 去掉transform，直接设置左对齐
      style.left = `20px`
      style.transform = 'none'
    }

    // 垂直位置调整 - 智能决定显示在上方还是下方
    const spaceAbove = props.selectionRect.top
    const spaceBelow = viewportHeight - props.selectionRect.bottom
    const requiredSpace = toolbarHeight + gap

    if (spaceAbove >= requiredSpace) {
      // 上方有足够空间，显示在选区上方
      style.top = `${props.selectionRect.top + window.scrollY - toolbarHeight - gap}px`
    } else if (spaceBelow >= requiredSpace) {
      // 下方有足够空间，显示在选区下方
      style.top = `${props.selectionRect.bottom + window.scrollY + gap}px`
    } else {
      // 两边空间都不够，选择空间较大的一边
      if (spaceAbove > spaceBelow) {
        style.top = `${window.scrollY + gap}px` // 贴近视口顶部
      } else {
        style.top = `${props.selectionRect.bottom + window.scrollY + gap}px` // 选区下方
      }
    }
  }

  return style
})

// 计算当前字体名称
const currentFontName = computed(() => {
  const font = fonts.find((f) => f.value === props.currentFormat.fontFamily)
  return font ? font.label : '宋体'
})

// 计算当前字体大小显示文本
const currentFontSizeText = computed(() => {
  const currentSize = props.currentFormat.fontSize
  if (!currentSize) return '16px'

  // 如果是数字，转换为px
  if (typeof currentSize === 'number') {
    return `${currentSize}px`
  }

  // 如果已经包含单位，直接返回
  if (typeof currentSize === 'string' && currentSize.includes('px')) {
    return currentSize
  }

  // 处理其他情况
  return currentSize || '16px'
})

// 判断是否应该右对齐下拉菜单
const shouldAlignRight = computed(() => {
  if (props.visible && props.position) {
    const toolbarX = props.position.x
    const viewportWidth = window.innerWidth
    const toolbarWidth = 520
    const halfWidth = toolbarWidth / 2

    // 检查工具栏是否被推到右边界或者整体靠右
    const isToolbarNearRightEdge = toolbarX + halfWidth > viewportWidth - 100

    // 或者检查工具栏是否在屏幕右半部分
    const isInRightHalf = toolbarX > viewportWidth * 0.5

    return isToolbarNearRightEdge || isInRightHalf
  }
  return false
})

// 根据当前模式返回相应的颜色数组
const currentColors = computed(() => {
  return colorMode.value === 'text' ? textColors : backgroundColors
})

const toggleFontDropdown = () => {
  showFontDropdown.value = !showFontDropdown.value
  showFontSizeDropdown.value = false
  showColorPicker.value = false
}

const toggleFontSizeDropdown = () => {
  showFontSizeDropdown.value = !showFontSizeDropdown.value
  showFontDropdown.value = false
  showColorPicker.value = false
}

const toggleColorPicker = () => {
  showColorPicker.value = !showColorPicker.value
  showFontDropdown.value = false
  showFontSizeDropdown.value = false
}

const setColorMode = (mode) => {
  colorMode.value = mode
}

const applyFormat = (type, value) => {
  emit('format', { type, value })
  // 延迟关闭下拉菜单，让格式化操作先完成
  setTimeout(() => {
    showFontDropdown.value = false
    showFontSizeDropdown.value = false
    showColorPicker.value = false
  }, 100)
}

// 应用字体大小
const applyFontSize = (size) => {
  applyFormat('fontSize', size.value)
}

// 应用颜色格式
const applyColorFormat = (color) => {
  const formatType = colorMode.value === 'text' ? 'color' : 'backgroundColor'
  emit('format', { type: formatType, value: color })
}

// 判断颜色是否激活
const isColorActive = (color) => {
  if (colorMode.value === 'text') {
    return props.currentFormat.color === color
  } else {
    return props.currentFormat.backgroundColor === color
  }
}

// 获取颜色标题
const getColorTitle = (color) => {
  if (color === 'inherit' || color === 'transparent') {
    return colorMode.value === 'text' ? '默认文字颜色' : '透明背景'
  }
  return color
}

// 获取自定义颜色值
const getCustomColorValue = () => {
  if (colorMode.value === 'text') {
    return props.currentFormat.color || '#000000'
  } else {
    return props.currentFormat.backgroundColor || '#ffffff'
  }
}

// 应用自定义颜色
const applyCustomColor = (event) => {
  const color = event.target.value
  applyColorFormat(color)
}

// 重置颜色
const resetColor = () => {
  if (colorMode.value === 'text') {
    applyColorFormat('inherit')
  } else {
    applyColorFormat('transparent')
  }
}

const insertLink = () => {
  emit('insert-link')
}

const showMoreOptions = () => {
  emit('more-options')
}

// 关闭下拉菜单
const closeDropdowns = (event) => {
  if (!event.target.closest('.dropdown-container')) {
    showFontDropdown.value = false
    showFontSizeDropdown.value = false
    showColorPicker.value = false
  }
}

// 监听可见性变化
watch(
  () => props.visible,
  (newVal) => {
    if (!newVal) {
      showFontDropdown.value = false
      showFontSizeDropdown.value = false
      showColorPicker.value = false
    }
  }
)

onMounted(() => {
  document.addEventListener('click', closeDropdowns)
})

onUnmounted(() => {
  document.removeEventListener('click', closeDropdowns)
})
</script>

<style scoped>
.inline-toolbar {
  position: fixed !important;
  z-index: 50000 !important;
  display: flex !important;
  align-items: center !important;
  gap: 2px !important;
  padding: 4px 6px !important;
  background: white !important;
  border: 1px solid #e5e7eb !important;
  border-radius: 8px !important;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15), 0 4px 10px rgba(0, 0, 0, 0.1) !important;
  user-select: none !important;
}

.toolbar-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 2px;
  padding: 6px 8px;
  background: transparent;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.15s ease;
  color: #374151;
  position: relative;
}

.toolbar-btn:hover {
  background: #f3f4f6;
  color: #d7000f;
}

.toolbar-btn.active {
  background: #d7000f;
  color: white;
}

.toolbar-btn.active:hover {
  background: #b8000d;
  color: white;
}

.icon {
  width: 16px;
  height: 16px;
}

.icon-small {
  width: 10px;
  height: 10px;
}

.toolbar-divider {
  width: 1px;
  height: 20px;
  background: #e5e7eb;
  margin: 0 4px;
}

.dropdown-container {
  position: relative;
}

.dropdown-menu {
  position: absolute !important;
  top: 100% !important;
  left: 0 !important;
  margin-top: 4px !important;
  background: white !important;
  border: 1px solid #e5e7eb !important;
  border-radius: 6px !important;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15) !important;
  z-index: 999999 !important;
  min-width: 150px !important;
  max-height: 300px !important;
  overflow-y: auto !important;
  display: block !important;
  visibility: visible !important;
}

.font-dropdown {
  width: 180px;
}

.font-size-dropdown {
  width: 160px;
}

.dropdown-item {
  padding: 8px 12px;
  cursor: pointer;
  transition: all 0.15s ease;
  font-size: 14px;
}

.dropdown-item:hover {
  background: #f3f4f6;
  color: #7f094a;
}

.dropdown-item.active {
  background: #7f094a;
  color: white;
}

/* 颜色选择器下拉菜单 */
.color-picker-dropdown {
  width: 280px;
  padding: 0;
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

/* 颜色模式标签 */
.color-mode-tabs {
  display: flex;
  border-bottom: 1px solid #e5e7eb;
  background: #f9fafb;
}

.color-tab {
  flex: 1;
  padding: 10px 16px;
  background: transparent;
  border: none;
  cursor: pointer;
  font-size: 13px;
  font-weight: 500;
  color: #6b7280;
  transition: all 0.15s ease;
  position: relative;
}

.color-tab:hover {
  background: rgba(215, 0, 15, 0.05);
  color: #d7000f;
}

.color-tab.active {
  background: white;
  color: #d7000f;
  font-weight: 600;
}

.color-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: #d7000f;
}

/* 颜色内容区域 */
.color-content {
  padding: 16px;
}

/* 自定义颜色区域 */
.custom-color-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
}

.custom-color-title {
  font-size: 12px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
}

.custom-color-input {
  width: 40px;
  height: 32px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 8px;
  background: transparent;
  padding: 0;
  vertical-align: middle;
}

.custom-color-input:hover {
  border-color: #d7000f;
}

.reset-color-btn {
  padding: 6px 12px;
  background: #f3f4f6;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  font-size: 12px;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.15s ease;
  vertical-align: middle;
}

.reset-color-btn:hover {
  background: #e5e7eb;
  color: #374151;
  border-color: #d1d5db;
}

.color-dropdown {
  width: 200px;
  padding: 8px;
}

/* 字体大小按钮样式 */
.font-size-btn {
  min-width: 80px;
  justify-content: space-between;
  gap: 4px;
}

.font-size-text {
  font-size: 12px;
  font-weight: 500;
}

.size-label {
  flex: 1;
}

.size-value {
  font-size: 11px;
  color: #6b7280;
}

/* 右对齐的下拉菜单 */
.dropdown-right {
  right: 0 !important;
  left: auto !important;
}

.color-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 6px;
  margin-bottom: 8px;
}

.color-item {
  width: 32px;
  height: 32px;
  border: 2px solid transparent;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.15s ease;
  position: relative;
}

.color-item:hover {
  transform: scale(1.1);
  border-color: #7f094a;
}

.color-item.active {
  border-color: #7f094a;
  box-shadow: 0 0 0 2px rgba(127, 9, 74, 0.2);
}

/* 特殊的透明/默认颜色选项样式 */
.color-item[style*='inherit'],
.color-item[style*='transparent'] {
  background: linear-gradient(
    135deg,
    transparent 48%,
    #ff0000 48%,
    #ff0000 52%,
    transparent 52%
  ) !important;
  border: 1px solid #e5e7eb !important;
}

/* 颜色选择器按钮 */
.color-picker-btn {
  min-width: 60px;
  justify-content: space-between;
  gap: 4px;
}

.color-indicators {
  display: flex;
  gap: 2px;
  margin-left: 4px;
}

.color-indicator {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  border: 1px solid #e5e7eb;
  position: relative;
}

.color-indicator.text-color {
  order: 1;
}

.color-indicator.bg-color {
  order: 2;
}

/* 透明背景的特殊处理 */
.color-indicator.bg-color[style*='transparent'] {
  background: linear-gradient(
    135deg,
    transparent 48%,
    #ff0000 48%,
    #ff0000 52%,
    transparent 52%
  ) !important;
}

.color-dropdown-title {
  font-size: 12px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  padding: 8px 0 4px 0;
  border-bottom: 1px solid #f0f0f0;
}

/* 字体选择按钮样式 */
.font-btn {
  min-width: 100px;
  justify-content: space-between;
  gap: 4px;
}

.font-name {
  font-size: 12px;
  font-weight: 500;
  max-width: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 过渡动画 */
.toolbar-fade-enter-active,
.toolbar-fade-leave-active {
  transition: opacity 0.2s ease, transform 0.2s ease;
}

.toolbar-fade-enter-from,
.toolbar-fade-leave-to {
  opacity: 0;
  transform: translateX(-50%) translateY(-10px);
}

/* 响应式设计 */
@media (max-width: 640px) {
  .inline-toolbar {
    gap: 1px;
    padding: 3px 4px;
  }

  .toolbar-btn {
    padding: 4px 6px;
  }

  .icon {
    width: 14px;
    height: 14px;
  }

  .toolbar-divider {
    margin: 0 2px;
  }

  .color-picker-dropdown {
    width: 260px;
  }

  .color-grid {
    grid-template-columns: repeat(5, 1fr);
    gap: 4px;
  }

  .color-item {
    width: 28px;
    height: 28px;
  }

  .color-content {
    padding: 12px;
  }

  .custom-color-section {
    margin-top: 12px;
    padding-top: 12px;
  }
}
</style>
